//
//  ICCLLocation.swift
//  ICCLLocationDemo
//
//  Created by cc on 2018/7/19.
//  Copyright © 2018年 cc. All rights reserved.
//

import UIKit
import CoreLocation
///只返回经纬度
typealias locationMod = (lat: Double?, lon: Double?)
///详细的地址信息返回
typealias responseCompletion<T> = (_ response: T) -> Void

/// 使用频率
///
/// - inUse: 只调用一次
/// - always: 一直获取
enum ICLocationUseType {
    case inUse, always
}
class ICCLLocation: NSObject {
    var locationCompletion: responseCompletion<ICLocationModel?>?
    var coordinateCompletion: responseCompletion<locationMod>?
    let locationManager = CLLocationManager()
    private var mod : locationMod? = nil
    var useType: ICLocationUseType = .always
    lazy var geocoder: CLGeocoder = {
       return CLGeocoder()
    }()
    
    override init() {
        super.init()
       
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //定位精度
        locationManager.distanceFilter = 10
        
        authorizationVerify()
    }
    
    public func locationStart() {
        locationManager.startUpdatingLocation()
    }
    public func locationStop() {
        locationManager.stopUpdatingLocation()
    }
    
    func authorizationVerify() {
        if CLLocationManager.locationServicesEnabled() == false {
            print("请确认已开启定位服务")
            return
        }
        
        if CLLocationManager.authorizationStatus() == .notDetermined {
            locationManager.requestAlwaysAuthorization()
        }

    }
    
    func geocoderLocation(_ lo: CLLocation)  {
        guard locationCompletion != nil else { return }
        geocoder.reverseGeocodeLocation(lo) { (placemarks, err) in
            if let marks = placemarks {
                var mod: ICLocationModel?
                for placemark in marks {
                    mod = ICLocationModel(placemark)
                }
                self.locationCompletion!(mod!)
            }else {
                print("地址解析失败")
                self.locationCompletion!(nil)
            }
            
        }
    }
    
    public func geocoderAddress(_ address: String) {
        geocoder.geocodeAddressString(address) { (placemarks, err) in
            if let marks = placemarks {
                for placemark in marks {
                    print(placemark)
                    
                }
            }
        }
    }
    

    
}


extension ICCLLocation: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if useType == .inUse {
            manager.stopUpdatingLocation()
        }
        let lo = locations.first
        let mod: locationMod = (lo?.coordinate.latitude, lo?.coordinate.longitude)
        coordinateCompletion?(mod)
        geocoderLocation(lo!)
        
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
}






